<template>
  <div>
    <el-card>
      <el-scrollbar :height="height" ref="scrollbarRef">
        <el-tabs v-model="activeName" @tab-change="tabChange">
          <el-tab-pane label="添加控件" name="first">
            <el-form ref="propertiesRef" :model="propertiesForm" :rules="rules" label-width="85">
              <el-form-item label="控件类型：" prop="componentType">
                <el-select v-model="propertiesForm.componentType" placeholder="请选择控件类型" clearable
                  @change="componentTypeChange">
                  <el-option v-for="dict in sys_field_type" :key="dict.value" :label="dict.label"
                    :value="parseInt(dict.value)"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="控件名称：" prop="componentName">
                <el-input v-model="propertiesForm.componentName" placeholder="请输入控件名称" clearable />
              </el-form-item>
              <el-form-item label="默认值：" prop="defaultValue" v-if="propertiesForm.componentType === 2 ||
                propertiesForm.componentType === 1
                ">
                <el-input clearable v-model="propertiesForm.defaultValue" placeholder="请输入默认值"></el-input>
              </el-form-item>
              <el-form-item label="文本类型：" prop="dataType" v-if="propertiesForm.componentType === 1">
                <el-checkbox v-model="propertiesForm.dataType" label="长文本类型" size="large" style="height: 0;" />
              </el-form-item>
            </el-form>

            <el-row v-if="propertiesForm.componentType === 3 ||
              propertiesForm.componentType === 4 ||
              propertiesForm.componentType === 5
              ">
              <p class="pinformation">
                {{
                  propertiesForm.componentType == 3
                  ? "单选"
                  : propertiesForm.componentType == 4
                    ? "复选"
                    : "下拉框"
                }}控件
              </p>
              <!-- <p class="totalStyle">共 {{ radioControl.length }} 条数据</p> -->
              <el-row style="padding-bottom: 5px; margin-left: 10px">
                <el-button link type="success" icon="plus" @click="addOptionList">新增</el-button>
              </el-row>
            </el-row>
            <el-table class="business" :data="propertiesForm.optionList" v-if="propertiesForm.componentType === 3 ||
              propertiesForm.componentType === 4 ||
              propertiesForm.componentType === 5
              ">
              <el-table-column label="序号" type="index" width="55" align="center" />
              <el-table-column label="内容" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.optionLabel"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="默认值" align="center" width="70">
                <template #default="scope">
                  <el-checkbox v-model="scope.row.isSelected" label="" size="large" @change="isSelectedChange(scope)" />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="80">
                <template #default="scope">
                  <el-button link icon="Delete" @click="deleteOptionListRow(scope)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row justify="center" style="margin-top: 15px">
              <el-button type="success" @click="define">确 定</el-button>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="字段列表" name="second">
            <el-row style="justify-content: end; margin-bottom: 5px">
              <el-button type="success" @click="orderSave" size="small">保存</el-button>
            </el-row>
            <el-collapse v-model="activeNames">
              <el-collapse-item :title="index ? '子表字段' : '主表字段'" :name="index + 1" v-for="(props, index) in fieldList">
                <ul :id="'sortable-list' + index" class="list-group" style="margin: 0">
                  <li class="list-group-item" style="padding: 5px 0" v-for="(item, index) in props.subFieldList"
                    :key="index" v-if="!!props.subFieldList.length" :data-id="item.componentId">
                    <span style="margin-left: 20px">{{
                      item.componentName
                    }}</span>
                  </li>
                  <el-row style="justify-content: center" v-else>
                    <span>暂无数据</span>
                  </el-row>
                </ul>
              </el-collapse-item>
            </el-collapse>
          </el-tab-pane>

          <el-tab-pane label="前处理条件" name="foure">
            <el-table :data="conditionList">
              <el-table-column label="序号" type="index" width="55" align="center" />
              <el-table-column label="条件变量" align="center" prop="conditionName" />
              <el-table-column label="控件" align="center">
                <template #default="scope">
                  <el-select v-model="scope.row.componentId" placeholder="请选择控件类型" clearable>
                    <el-option v-for="item in componentList" :key="item.componentId" :label="item.componentName"
                      :value="item.componentId"></el-option>
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="javascript脚本" name="third">
            <el-row style="justify-content: space-between; margin-bottom: 5px">
              <p class="pinformation" style="margin-top: 7px">
                javascript脚本
              </p>
              <el-button type="success" @click="handleSumit">保存</el-button>
            </el-row>
            <Codemirror v-model:value="code" :options="extensions" border :height="600" />
          </el-tab-pane>
        </el-tabs>
        <div style="height: 40px;"></div>
        <div style="position: absolute; bottom: 0;width: 100%; padding-right: 10px;height: 40px;
          text-align: left;z-index: 2000;">
          <el-button type="success" link @click="contractClick" style="line-height: 40px;">
            收起<el-icon>
              <DArrowRight />
            </el-icon>
          </el-button>
        </div>
      </el-scrollbar>
    </el-card>
  </div>
</template>

<script setup>
import bus from "@/utils/eventBus";
import { getSeqId } from "@/api/common";
import {
  getComponentList,
  postNumber,
  getConditionList,
} from "@/api/templateEditor/right.js";
import { saveJsTable } from "@/api/templateEditor/table.js";
import Sortable from "sortablejs";
// javascript 脚本引入
import Codemirror from "codemirror-editor-vue3";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/monokai.css";
import "codemirror/mode/javascript/javascript";
import "codemirror/addon/hint/show-hint.css";
import "codemirror/addon/hint/show-hint";
import "codemirror/addon/hint/javascript-hint";
import { nextTick } from "vue";

const route = useRoute();
const { proxy } = getCurrentInstance();
const propertiesForm = ref({ optionList: [] });
const activeNames = ref(1);
const componentList = ref([]);
const conditionList = ref([]);
const fieldList = ref([
  { name: "主表字段", subFieldList: [] },
  { name: "字表字段", subFieldList: [] },
]);
const activeName = ref("first");
const { sys_field_type } = proxy.useShareDict("sys_field_type");
const rules = ref({
  componentType: [
    { required: true, message: "控件类型不能为空", trigger: "blur" },
  ],
  componentName: [
    { required: true, message: "控件名称不能为空", trigger: "blur" },
  ],
});

function contractClick() {
  bus.emit("contractClick", "right");
}

const height = ref();

function getHeight() {
  nextTick(() => {
    height.value = proxy.getSubFileHeight(proxy, "scrollbarRef");
  });
}

function listCondition() {
  getConditionList(route.query.tableId).then((res) => {
    conditionList.value = res.data;
  });
}

listCondition();

bus.off("getconditionList");
bus.on("getconditionList", (val) => {
  let temp = conditionList.value.filter((item) => {
    return item.componentId;
  });
  val.conditionList = temp;
});

bus.on("tempComponent", (val) => {
  componentList.value = val.filter((item) => {
    return item.isHide == 0;
  });
  if (componentList.value.length === 0) return;
  conditionList.value.forEach((item) => {
    if (!item.componentId) {
      componentList.value.forEach((item1) => {
        if (item.conditionName == item1.componentName) {
          item.componentId = item1.componentId;
        }
      });
    }
    if (item.componentId && componentList.value[0].del === 1) {
      if (
        !componentList.value.find(
          (item1) => item1.componentId == item.componentId
        )
      ) {
        item.componentId = "";
      }
    }
  });
});

function define() {
  proxy.$refs["propertiesRef"].validate((valid) => {
    if (!valid) {
      return false;
    }
    if (
      propertiesForm.value.componentType === 3 ||
      propertiesForm.value.componentType === 4 ||
      propertiesForm.value.componentType === 5
    ) {
      delete propertiesForm.value.dataType
      if (propertiesForm.value.optionList.length) {
        for (const item of propertiesForm.value.optionList) {
          if (!item.optionLabel) {
            proxy.$modal.msgError("请将控件表格中内容补充完整");
            return false;
          }
        }
      } else {
        proxy.$modal.msgError("控件表格中至少存在一条");
        return false;
      }
    }
    if (propertiesForm.value.componentType === 4) {
      delete propertiesForm.value.dataType
      if (propertiesForm.value.optionList.length > 0) {
        propertiesForm.value.optionList.forEach((item) => {
          if (item.isSelected) {
            item.selected = 1;
          } else {
            item.selected = 0;
          }
        });
      }
    }
    // if (
    //   propertiesForm.value.componentType === 1
    // ) {
    //   if (propertiesForm.value.dataType1) {
    //     propertiesForm.value.dataType = 1
    //   } else {
    //     propertiesForm.value.dataType = 0
    //   }
    // }
    if (propertiesForm.value.componentType === 2) {
      delete propertiesForm.value.dataType
    }
    if (!propertiesForm.value.componentId) {
      getSeqId().then((res) => {
        propertiesForm.value.componentId = res.data;
        propertiesForm.value.sourceType = 3;
        bus.emit(
          "handleField",
          JSON.parse(JSON.stringify(propertiesForm.value))
        );
      });
    } else {
      bus.emit("handleField", JSON.parse(JSON.stringify(propertiesForm.value)));
    }
  });
}

bus.off("setPropertiesForm");
bus.on("setPropertiesForm", (formData) => {
  if (formData.componentType) {
    propertiesForm.value = formData;
    // if (propertiesForm.value.dataType) {
    //   propertiesForm.value.dataType1 = true
    // } else {
    //   propertiesForm.value.dataType1 = false
    // }
    propertiesForm.value.optionList?.forEach((item) => {
      if (item.selected) {
        item.isSelected = true;
      } else {
        item.isSelected = false;
      }
    });
  } else {
    propertiesForm.value = { componentType: 1, dataType: false };
  }
  proxy.$refs["propertiesRef"].clearValidate();
});

function addOptionList() {
  propertiesForm.value.optionList.push({});
}

function componentTypeChange() {
  propertiesForm.value.optionList = [];
  propertiesForm.value.defaultValue = "";
  propertiesForm.value.dataType = false;
}

function deleteOptionListRow(scope) {
  propertiesForm.value.optionList.splice(scope.$index, 1);
}

onMounted(() => {
  nextTick(() => {
    getHeight();
    window.addEventListener("resize", getHeight);
  });
});
onUpdated(() => {
  getHeight();
  window.addEventListener("resize", getHeight);
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getHeight);
});

const subFieldList0 = ref([]);
const subFieldList1 = ref([]);

function tabChange(name) {
  if (name == "second") {
    getList().then(() => {
      nextTick(() => {
        const sortable = new Sortable(
          document.getElementById("sortable-list0"),
          {
            animation: 150,
            onEnd: function () {
              const items = sortable.toArray();
              subFieldList0.value = items.map((id) =>
                fieldList.value[0].subFieldList.find(
                  (item) => item.componentId === id
                )
              );
            },
          }
        );
        const sortable1 = new Sortable(
          document.getElementById("sortable-list1"),
          {
            animation: 150,
            onEnd: function () {
              const items = sortable1.toArray();
              subFieldList1.value = items.map((id) =>
                fieldList.value[1].subFieldList.find(
                  (item) => item.componentId === id
                )
              );
            },
          }
        );
      });
    });
  }
}

function getList() {
  return new Promise((resolve, reject) => {
    getComponentList({ tableId: route.query.tableId }).then((res) => {
      fieldList.value[0].subFieldList = []
      fieldList.value[1].subFieldList = []
      subFieldList0.value = []
      subFieldList1.value = []
      nextTick(() => {
        fieldList.value[0].subFieldList = res.data.parentList;
        fieldList.value[1].subFieldList = res.data.childList;
        subFieldList0.value = res.data.parentList;
        subFieldList1.value = res.data.childList;
        resolve();
      })
    });
  });
}

function orderSave() {
  subFieldList0.value.forEach((item, index) => {
    item.orderId = index + 1;
    item.tableId = route.query.tableId;
  });
  subFieldList1.value.forEach((item, index) => {
    item.orderId = index + 1 + fieldList.value[0].subFieldList.length;
    item.tableId = route.query.tableId;
  });
  let tempList = subFieldList0.value.concat(subFieldList1.value);
  postNumber(tempList).then((res) => {
    proxy.$modal.msgSuccess("保存成功");
  });
}

// 脚本控件代码
const code = ref("");
const extensions = ref({
  mode: "javascript", // 语言模式
  theme: "monokai", // 主题
  lineNumbers: true, // 显示行号
  smartIndent: true, // 智能缩进
  readOnly: false,
  indentUnit: 4, // 智能缩进单位为4个空格长度
  foldGutter: true, // 启用行槽中的代码折叠
  styleActiveLine: true, // 显示选中行的样式
  "Ctrl-Alt": javascriptHint,
});

function javascriptHint(cm) {
  CodeMirror.showHint(cm, CodeMirror.hint.javascript);
}

function handleSumit() {
  saveJsTable({ tableId: route.query.tableId, jsContent: code.value }).then(
    (res) => {
      proxy.$modal.msgSuccess("保存成功！");
    }
  );
}

bus.off("setCodeValue");
bus.on("setCodeValue", (codeValue) => {
  if (!codeValue) {
    code.value = " ";
    return;
  }
  code.value = codeValue;
});

function isSelectedChange(scope) {
  if (propertiesForm.value.componentType != 4) {
    if (scope.row.isSelected) {
      propertiesForm.value.optionList.forEach((item) => {
        item.isSelected = false;
        item.selected = 0;
      });
      propertiesForm.value.optionList[scope.$index].isSelected = true;
      propertiesForm.value.optionList[scope.$index].selected = 1;
    }
  }
}

</script>
